<template>
  <div class="deviceManage_list">
    <maintain-device ref="MaintainDevice"
                     :staffList="staffList"
                     :MaintainPorject="MaintainPorject"
                     @success="maintainSuccess"></maintain-device>
    <repair-device ref="RepairDevice"
                   :staffList="staffList"
                   :RepairProject="RepairProject"
                   @success="repairSuccess"></repair-device>
    <scrap-device ref="ScrapDevice"></scrap-device>
    <one-title title="设备台账管理" @refreshData="refresh">
      <div class="mes_btn">
        <el-tooltip
          effect="dark"
          :open-delay="openDelay"
          :content="deviceBtnStatus.content"
          :disabled="!deviceBtnStatus.status"
          popper-class="btn_tooltip"
          placement="bottom">
          <el-button
            v-btn-permission="'scrap'"
            @click="scrapDevice" :class="{'is-disabled':deviceBtnStatus.status}">
            <i class="iconfont icon-btn_delete"></i>
            报废
          </el-button>
        </el-tooltip>
        <el-tooltip
          effect="dark"
          :open-delay="openDelay"
          :content="deviceBtnStatus.content"
          :disabled="!deviceBtnStatus.status"
          popper-class="btn_tooltip"
          placement="bottom">
          <el-button
            v-btn-permission="'repair'"
            @click="repairDevice" :class="{'is-disabled':deviceBtnStatus.status}">
            <i class="iconfont icon-weixiu"></i>
            维修
          </el-button>
        </el-tooltip>
        <el-tooltip
          effect="dark"
          :open-delay="openDelay"
          :content="deviceBtnStatus.content"
          :disabled="!deviceBtnStatus.status"
          popper-class="btn_tooltip"
          placement="bottom">
          <el-button
            v-btn-permission="'maintain'"
            @click="maintainDevice" :class="{'is-disabled':deviceBtnStatus.status}">
            <i class="iconfont icon-baoyang"></i>
            保养
          </el-button>
        </el-tooltip>
        <el-button
          v-btn-permission="'import'"
          class="upload_btn" @click="fileUpload">
          <i class="iconfont icon-btn_import"></i>
          <span class="btn_name">导入</span>
        </el-button>
        <el-tooltip
          effect="dark"
          :content="editBtnStatus.content"
          :disabled="!editBtnStatus.status"
          popper-class="btn_tooltip"
          placement="bottom">
          <el-button
            v-btn-permission="'edit'"
            @click="_edit" :class="{'is-disabled':editBtnStatus.status}">
            <i class="iconfont icon-btn_edit"></i>
            修改
          </el-button>
        </el-tooltip>
        <el-button
          v-btn-permission="'add'"
          type="success" @click="_add">
          <i class="iconfont icon-btn_addnew"></i>
          新增
        </el-button>
      </div>
    </one-title>
    <div class="fixed_top_56">
      <mes-search-comp
        ref="mesSearch"
        @searchInfo="_info"
        :searchList="tableColConfig"
        :searchResult="searchResult">
      </mes-search-comp>
      <div class="table_container">
        <el-table
          :data="listData.list"
          border
          stripe
          v-loading="isLoading"
          :max-height="tableMaxHeight"
          @sort-change="_sort"
          tooltip-effect="dark"
          align="center"
          ref="tableNode"
          :row-class-name="({row}) => !selectData.some((item) => item.id === row.id) || 'line_selected'"
          @row-click="(row) => $refs.tableNode.toggleRowSelection(row)"
          @selection-change="handleSelectionChange"
          @filter-change="handleFilterChange">
          <el-table-column
            width="40"
            type="selection"
            align="center">
          </el-table-column>
          <mes-col-comp
            :key="index"
            v-for="(column,index) in columnList"
            :column="column"
            @jump="row => $linkToDetail(row, 'deviceManageDetail')">
          </mes-col-comp>
          <!--<el-table-column-->
          <!--prop="devicePower"-->
          <!--label="功率"-->
          <!--show-overflow-tooltip-->
          <!--align="center">-->
          <!--<template slot-scope="scope">-->
          <!--<span>{{scope.row.devicePower || ''}}</span>-->
          <!--</template>-->
          <!--</el-table-column>-->
          <!--<el-table-column-->
          <!--prop="deviceLifetime"-->
          <!--label="使用寿命"-->
          <!--show-overflow-tooltip-->
          <!--align="center">-->
          <!--<template slot-scope="scope">-->
          <!--<span>{{scope.row.deviceLifetime ? scope.row.deviceLifetime + '年' : ''}}</span>-->
          <!--</template>-->
          <!--</el-table-column>-->
          <!--<el-table-column-->
          <!--prop="maintainPeriod"-->
          <!--label="保养周期"-->
          <!--show-overflow-tooltip-->
          <!--align="center">-->
          <!--<template slot-scope="scope">-->
          <!--<span>{{scope.row.maintainPeriod ? scope.row.maintainPeriod + '月' : ''}}</span>-->
          <!--</template>-->
          <!--</el-table-column>-->
        </el-table>
      </div>
      <mes-pagination
        @updateData="init"
        :currentPage="listData.pageNo"
        :total="listData.count || 0"
        :pageSize="listData.pageSize">
      </mes-pagination>
    </div>
    <!--设备导入-->
    <resource-manage-upload ref="ResourceManageUpload" @importSuccess="init"></resource-manage-upload>
  </div>
</template>
<script>
import {DeviceStatus} from '@/components/mesDict'
import ResourceManageUpload from '@/components/resourceManageUpload/ResourceManageUpload'
import {MaintainDevice, RepairDevice, ScrapDevice} from './components'
import tableColumn from './components/tableColumn'

// 维修中
const Repair = 'Repair'
// 保养中
const Maintain = 'Maintain'
// 报废
const Abandoned = 'Abandoned'
export default {
  name: 'DeviceManage',
  data() {
    return {
      tableColConfig: tableColumn, // 列配置
      isLoading: true, // 数据加载
      selectData: [], // 选中的工厂名称
      sortData: {}, // 排序
      searchData: {}, // 搜索的字段
      searchResult: NaN, // 搜索结果数
    }
  },
  components: {
    DeviceStatus,
    MaintainDevice,
    RepairDevice,
    ScrapDevice,
    ResourceManageUpload
  },
  computed: {
    // 获取列表数据
    listData() {
      return this.$store.state.deviceManage.listData
    },
    // 设备状态
    deviceStatus() {
      return this.$store.state.dict.DeviceStatus.labels || []
    },
    // 保养项目
    MaintainPorject() {
      return this.$store.state.dict.MaintainPorject.labels || []
    },
    // 维修项目
    RepairProject() {
      return this.$store.state.dict.RepairProject.labels || []
    },
    // 人员列表
    staffList() {
      const list = this.$store.state.deviceManage.staffList.list || []
      return list.map((item) => {
        return {
          ID: item.id,
          NAME: item.name
        }
      })
    },
    // 列循环
    columnList() {
      return this.tableColConfig.filter(item => item.noForCol !== true && item.isShow !== false)
    },
    // 修改按钮
    editBtnStatus() {
      let status = this.selectData.length > 1 || this.selectData.some((item) => item.deviceStatusValue === 'Abandoned')
      return {
        status: status,
        content: '请选择一条非报废设备数据'
      }
    },
    // 保养、维修、报废按钮
    deviceBtnStatus() {
      let status = false
      if (this.selectData.some(item => item.deviceStatusValue !== 'Normal')) {
        status = true
      }
      return {
        status: status,
        content: '请选择设备状态为“正常”的数据'
      }
    },
  },
  mounted() {
    this.getStaff()
    this.init()
  },
  methods: {
    // 列筛选回调
    handleFilterChange(filters) {
      let filterParams = this.$filterParams(this.tableColConfig, filters)
      Object.assign(this.searchData, filterParams.search)
      this.sortData = filterParams.order // 排序对象
      this.$refs.tableNode.clearSort()
      this.init()
    },
    // 刷新方法
    refresh() {
      this.searchData = {}
      this.sortData = {}
      this.$refs.mesSearch.clean()
      this.$refs.tableNode.clearSort()
      this.$refs.tableNode.clearFilter()
      this.init()
    },
    // 初始化方法
    init(page) {
      let postData = {
        method: 'post',
        url: 'a/device/device/list',
        data: {
          pageNo: page ? page.pageNo : 1,
          pageSize: page ? page.pageSize : this.listData.pageSize || 15,
          query: {
            delFlag: 0
          }
        },
        module: 'deviceManage',
        state: 'listData'
      }
      if (Object.keys(this.searchData).length > 0) {
        postData.data.query = this.searchData
      }
      if (Object.keys(this.sortData).length > 0) {
        postData.data.sort = this.sortData
      }
      this.$store.dispatch('saveData', postData).then((res) => {
        if (Object.keys(this.searchData).length > 0) {
          this.searchResult = res.count
        } else {
          this.searchResult = NaN
        }
      }).finally(() => {
        this.isLoading = false
      })
    },
    // 获取人员列表
    getStaff() {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/staff/staff/list',
        data: {
          pageNo: 1,
          pageSize: 9999,
          query: {
            columns: ['name']
          },
          sort: { name: 'asc' }
        },
        module: 'deviceManage',
        state: 'staffList'
      })
    },
    // 查询
    _info(data) {
      this.searchData = data
      this.init()
    },
    // 多选表格数据
    handleSelectionChange(val) {
      this.selectData = val
    },
    // 新增
    _add() {
      this.$router.push({
        path: 'deviceManageDetail'
      })
    },
    // 删除弹窗提示
    showDeleteDialog() {
      if (this.selectData.length > 0) {
        this.confirmDelete().then(() => {
          this.deleteList()
        })
      } else {
        this.$message({
          type: 'error',
          message: '未选中任何数据',
          duration: 1500,
          center: true
        })
      }
    },
    // 编辑
    _edit() {
      if (!this.selectData.length || this.selectData.length > 1) {
        return this.tipMessage('error', '请选择一条设备数据')
      }
      if (this.editBtnStatus.status) return
      this.$router.push({
        path: 'deviceManageDetail',
        query: {
          id: this.selectData[0].id
        }
      })
    },
    // 排序
    _sort(item) {
      this.sortData = this.$getSortOrder(item)
      this.init()
    },
    // 报废
    scrapDevice() {
      if (!this.selectData.length) {
        return this.tipMessage('error', '请选择设备后，再进行操作!')
      }
      if (this.deviceBtnStatus.status) return
      this.confirmOpen('选中的设备将被报废, 是否继续?', '报废提示').then(() => {
        this.changeStatus(Abandoned)
      })
    },
    // 维修
    repairDevice() {
      if (!this.selectData.length) {
        return this.tipMessage('error', '请选择设备后，再进行操作!')
      }
      if (this.deviceBtnStatus.status) return
      this.$refs.RepairDevice.openDialog()
    },
    // 维修提交
    repairSuccess(obj) {
      this.changeStatus(Repair, obj.repairEmployeeID, obj.repairProjectID)
    },
    // 保养
    maintainDevice() {
      if (!this.selectData.length) {
        return this.tipMessage('error', '请选择设备后，再进行操作!')
      }
      if (this.deviceBtnStatus.status) return
      this.$refs.MaintainDevice.openDialog()
    },
    // 保养提交
    maintainSuccess(obj) {
      this.changeStatus(Maintain, obj.maintainEmployeeID, obj.maintainProjectID)
    },
    // 修改设备状态
    changeStatus(state, userId, projectId) {
      let postData = {
        targetStatus: this.deviceStatus.find(item => item.value === state).id,
      }
      if (userId) postData.userId = userId
      if (projectId) postData.projectId = projectId
      postData.DeviceList = this.selectData.map(item => {
        return {
          id: item.id
        }
      })
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/device/device/changeStatus',
        data: postData,
        noCommit: true
      }).then(() => {
        this.tipMessage('success', '操作成功')
        switch (state) {
          case Maintain:
            this.$refs.MaintainDevice.dialogVisible = false
            break
          case Repair:
            this.$refs.RepairDevice.dialogVisible = false
            break
        }
        this.init()
      })
    },
    // 点击导入
    fileUpload() {
      const url = 'a/device/device/importdevice'
      this.$refs.ResourceManageUpload.openDialog('设备', url)
    },
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style scoped lang="less">
  .mes_btn .upload_btn {
    position: relative;
    overflow: hidden;

    span {
      &.icon_upload {
        position: absolute;
        left: 100%;
      }
    }
  }
</style>
